/*
 * this file is included in only in WebtopModule specifcally templates/Default/default.phtml
 */
var dragging = false;
var element = document.activeElement;
var imageUrl = "images/seniors/";

function Celebrio () {
    /*desktopscroller 
     *variable for storing instance of IscrollPlus
     *initialized in desktop.createIcons()
     */
    this.desktopscroller = null;
    
    this.desktop = {
        /*
         *element
         *variable where is stored only #desktop element
         *initialized in initfnc
         *
         */
        element : null,
        contextmenu : null,
        setElement : function(element) {
            celebrio.desktop.element = element;
        },
        getElement : function() {
            return celebrio.desktop.element;
        },
        
        getHeight : function() {
            return    $(window).height();
        },
        getWidth : function() {
            return    $(celebrio.desktop.element).width();
        },
        /*
         *celebrio.desktop.display
         *sets width and height of #desktop element(stored in variable id)
         *loads background image
         *there is some implicit background on the page
         *after bacground image is loaded, imlicit background is deleted and replaced by the background image
         *called in initfnc+
         *called on initialization and on window.resize
         */
        display : function(url) {
            id = celebrio.desktop.getElement();
            id.width(celebrio.desktop.getWidth());
            id.height(celebrio.desktop.getHeight());
            appImage = new Image();
            appImage.onload = function() {
                $('#desktopBackground').remove();
                celebrio.image.stretch(appImage, $(window));
                $('<img src="'+url+'"  alt="'+url+'" width="'+window.innerWidth+'" height="'+window.innerHeight+'" id="desktopBackground" />').css({
                    position: "absolute",
                    zIndex:	-10,
                    left: 0,
                    top: 0
                }).appendTo("body");
            };
            appImage.src = url;
        },
        
        /*
         *celebrio.desktop.icons
         *variable where is stored instance of celebrio.icons object
         */
        icons : null,
        setColor : function(color) {
            $("body").css("backgroundColor", color);
        },
        
        /*
         *celebrio.desktop.createIcons()
         *initializes new object celebrio.icons, puts in it all icons and draws them
         *initializes celebrio.desktopscroller
         */
        createIcons : function () {
            //in id is stored element #desktop
            id = celebrio.desktop.getElement();
            
            //These values must be set as constants, because icons are not created yet!
            //the height of icon is computed from the value of dpi, the higher value if dpi is, the higher 
            height = 196*dpi/160 + 75; // 196 is constant height of icon image, dpi is global variable from userAgent dpi, 75 is size of margin and button
            width = 360;
            
            celebrio.desktop.icons = new celebrio.icons(id,width,height);
            $.getJSON(
                //getapps variable is defined in @layout.phtml of WebtopModule
                getapps,
                function (data) {
                    celebrio.desktop.icons.clear();
                    celebrio.desktop.icons.setCols(data.length);
                    $("#desktop").css({
                        "width" : data.length*width
                    });
                    if (!celebrio.desktopscroller) {
                        //iscroll
                        celebrio.desktopscroller = new IScrollPlus({
                            element : 'desktopWrapper'
                        });
                    } else {
                        celebrio.desktopscroller.refresh();
                    }
                    for (var i in data) {
                        app = data[i];
                        celebrio.desktop.icons.set(new celebrio.icon(app.name, app.icon, app.title, app.url, app.iconPath), i);
                    }
                    celebrio.scrollbar.init(celebrio.desktop.icons);
                    celebrio.desktop.icons.draw();
                    celebrio.desktop.checkHistory();
                    $(document).trigger('finishedload');
                });
        },
        
        checkHistory : function(){
            if (history.state) {
                state = history.state;
                url = location.hash.substring(1);
                //TODO: IE makes other urls!
                
                if (url.substring(0,4) != "http") {
                    url = url.substring(2);
                }
                celebrio.applications.run(state.name, state.title, url , {
                    'image' : state.image
                });
            }
        }
    },
	
    this.image = {
        
        resize : function(image, element) {
            proportions = {
                width : image.width,
                height : image.height
            };

            if(element.width() < image.width) {
                proportions.width = element.width();
                proportions.height = (element.width() / image.width) * image.height;
            }

            if(element.height() < image.height) {
                proportions.height = element.height();
                proportions.width = (element.height() / image.height) * image.width;
            }
            return proportions;
        },
        center : function(innerW, innerH, outerW, outerH) {
            return {
                left : ( outerW - innerW) / 2,
                top : ( outerH - innerH) / 2
            };
        },
        stretch : function(image, element) {
            image.width = element.width();
            image.height = element.height();
        }
    },
	
        
    /*
     *celebrio.icons
     *object that creates icons on the desktop
     *attr element is element where icons will be stored
     */
    this.icons = function(element, width, height) {
        this.width = width;
        this.height = height;
        this.element = element;
        this.cols = 0;
        this.icons = new Array();

        this.getWidth = function () {
            return this.width;
        };
        this.getHeight = function () {
            return this.height;
        };
        this.getCols = function () {
            return this.cols;
        };
        this.setCols = function (cols) {
            this.cols = cols;
        };


        /*
         * celebrio.icons.draw
         * for each icon in icons array creates html element and sets needes properties
         */
        this.draw = function () {            
            this.element.find(".albireoicon").remove();
            for ( i = 0; i < this.getCols();i++) {
                
                if (this.get(i) != null) {
                    this.get(i).element = $('<div class="albireoicon"></div>').appendTo(this.element).css(
                    {
                        top: Math.max(celebrio.desktop.getHeight()/2 - this.getHeight()/2,0),
                        left: i*this.getWidth(),
                        width: this.getWidth()
                    })
                    .attr("id", this.get(i).name)
                    .attr("name", this.get(i).url)
                    .html('<img src="'+this.get(i).image+'" class="iconimage" /><div class="iconName">' + this.get(i).getTitle() + '</div>')
                    .bind('click', function () {
                        if (!dragging) {

                            image = $(this).clone().html();	
                            helper = this;		
                            setTimeout(function(){
                                celebrio.applications.run($(helper).attr("id"), $(helper).find(".iconName").html(), $(helper).attr("name"), {
                                    'image' : $(image).attr("src")
                                });
                            },250);
                        }
                    });
                }
            }
        };
        
        /*
         * celebrio.desktop.icons.setFocus
         * retrieves all the iframes of the document
         * detects, which of iframes matches the url given as parameter app, and focus
         * content window of that iframe
         * Set focus to actualy running app
         */
        this.setFocus = function(app){
            var runningApps = (document).getElementsByTagName("iframe");
            setTimeout(function(){
                var beforeAppPort = app.substr(0, 16);
                var afterAppPort = app.substr(19, 50);
                var appAddress = beforeAppPort + afterAppPort;
                for (i=0;i<runningApps.length;i++) {
                    if(appAddress == runningApps[i].src){
                        //console.log("Predan focus: " + runningApps[i])
                        var runApp = runningApps[i].contentWindow;
                        setTimeout(function(){  // Because of IE
                            runApp.focus();
                        },1000);                        
                    }
                }
            },1);
        };
        
        /*
         *celebrio.icons.resize
         *vertical centralization if icons, if window height is changed
         *strange changes of #taskspace img
         */
        this.resize = function () {
            
            
            this.element.find(".albireoicon").css({
                top: Math.max(celebrio.desktop.getHeight()/2 - this.getHeight()/2,0)
            });

            $("#taskspace img").css({
                "height": ($("#taskspace").height() + 10), 
                "width" : "auto",
                "float" : "left",
                "margin" : "-20px 0px 0px 0px"
            });
                        	
            var iconWidth = $("#taskspace img").width();
            var totalWidth = $("#taskspace img").length * iconWidth;

            // Google Chrome compatibility
            if(iconWidth==0){
                iconWidth = 112;
            }

            $("#taskspace img").css({
                "marginLeft": (($("#taskspace").width() - (5*iconWidth))/10),
                "marginRight": (($("#taskspace").width() - (5*iconWidth))/10)-1
            });
            
            celebrio.scrollbar.resize(this);
        };

        this.set = function (icon,place) {
            this.icons[place] = icon;
        };
        this.get = function (place) {
            return this.icons[place];
        };
        this.clear = function () {
            this.icons = new Array();
        }
    },
	
    /*
     *celebrio.icon
     *object to store all needed information about icon
     */
    this.icon = function (name, image, title, url, path) {
        this.name = name;
        this.url = url;
        this.title = title;
        this.image = image;
        this.path = path;
        this.element = null;
	
        this.getName = function () {
            return this.name;
        };
	
        this.setName = function (name) {
            this.name = name;
        };
        
        this.getPath = function () {
            return this.path;
        };
	
        this.setPath = function (path) {
            this.path = path;
        };

        this.getTitle = function () {
            return this.title;
        };

        this.setTitle = function (title) {
            this.title = title;
        };
	
        this.getImage = function () {
            return this.image;
        };
	
        this.setImage = function (image) {
            this.image = image;
        };
    },
    

    /*
     *celebrio.scrollbar
     */
    this.scrollbar = {
        
        /*
         *celebrio.scrollbar.init
         *creates img elements for each icon and puts it into scrollbar
         *used in celebrio.desktop.createIcons()
         */
        "init" : function(icons){
            $("#scrollbar").find(".scrollbarImage").remove();
            var iconsWidth;
            var marginWidth;
            
            var image = new Image();

            image.onload = function() {
                iconsWidth = ((icons.getCols() * this.width));
                marginWidth = ($("#scrollbar").width() - iconsWidth) / (icons.getCols() * 2);
                iconOuterWidth = image.width + (marginWidth * 2);
                
                for (var i = 0; i < icons.getCols(); i++) {
                    $("#scrollbar").append('<img src="' + icons.get(i).path + 'scroller/icon.png' + '" id="scrollbarIcon' + i + '" class="scrollbarImage" />');

                    $("#scrollbarIcon" + i).css({
                        marginLeft : marginWidth,
                        marginRight : marginWidth
                    });

                    $("#scrollbarIcon" + i).css({
                        zIndex : 2,
                        position : "absolute",
                        left : i * iconOuterWidth,
                        marginTop : "5px",
                        marginBottom : "5px",
                        opacity : "0.15"
                    });
                    
                    $("#scrollbarIcon" + i).bind("dragstart", function(event){
                        event.preventDefault();
                    });
                };
                
                if (iconsWidth > $("#scrollbar").width()) {
                    $(".scrollbarImage").css({
                        display : "none"
                    });
                }
            }

            image.src = icons.get(0).path + 'scroller/icon.png';
        },
		
        /*
         *celebrio.scrollbar.resize
         *rewrites margins of scrollbars icons
         *called on window.resize event
         */
        "resize" : function(icons) {
            
            var iconsWidth = (($(".scrollbarImage").length * $(".scrollbarImage").width()));
            var marginWidth = ($("#scrollbar").width() - iconsWidth) /  ($(".scrollbarImage").length * 2);
            
            if(iconsWidth < $("#scrollbar").width()) {
                $(".scrollbarImage").css({
                    marginLeft: marginWidth,
                    marginRight: marginWidth
                });
                computePosition(icons);
                $(".scrollbarImage").fadeIn("slow");
            } else {
                computePosition(icons);
                $(".scrollbarImage").fadeOut("slow");
            }

            function computePosition (icons)  {
                for (var i = 0; i < icons.getCols(); i++) {
                    $("#scrollbarIcon" + i).css({
                        left : i * $("#scrollbarIcon" + i).outerWidth(true)
                    });
                }
            }
        }
    },
	
    this.applications = {
        APPLICATION : "application",
        /*
         *celebrio.applications.pid
         *process id, each process must have uniqe id
         *increased everytime process is created
         */
        pid : 0,
        /*
         *celebrio.applications.processes
         *array of running processes, process is added here when it is created,
         *removed from here, when closed
         */
        exitApplication : function exitApplication() {
            history.pushState(null, "title", "#");

            $(".dialogApplication").celebrioApp("minimize");
            $(".albireoicon").fadeIn("slow");
            $("#taskbar").fadeIn("slow");
            $("#scrollbar").fadeIn("slow");
            window.focus();
            setTimeout(window.focus, 0);
            //TODO: !!! HACK BECAUSE OF FIREFOX
            if ($.browser.mozilla) {
                $('<input type="text" id="focusButton"/>').appendTo('body');
                $("#focusButton").focus();
                $("#focusButton").remove();
            }
            // END OF HACK
            celebrio.desktop.icons.resize();
            return false;
        },
        processes : [],
        listeners : [],
        focus: null,
        kill : function (process) {
            $("#"+celebrio.applications.APPLICATION+process.getId()).remove();
            celebrio.arrays.remove(process,celebrio.applications.processes);
            
            console.log(loader);            
            loader.remove();
            
            // TODO this is copied from exit button click - refactor
            $(".dialogApplication").celebrioApp("minimize");
            $(".albireoicon").fadeIn("slow");
            $("#taskbar").fadeIn("slow");
            $("#scrollbar").fadeIn("slow");
            (window).focus();
            //Set focus back to webtop
            $("#task_"+process.name).remove();
            celebrio.desktop.icons.resize();
            history.pushState(null, "title", "#");
            return false;
            
        },
        
        /*
         *celebrio.applications.setFocus
         *if attr process is windowed, assign process into variable focus
         */
        setFocus : function (process) {
            if (process == null) {
                celebrio.applications.focus = null;
                return;
            }
            if(process.isWindowed()){
                celebrio.applications.focus = process;
            }
        },
        addAppListener : function (listener) {
            celebrio.applications.listeners.push(listener);
        },
        removeAppListener : function (listener) {
            celebrio.arrays.remove(listener, celebrio.applications.listeners);
        },
        addProcess : function (process) {
            celebrio.applications.processes.push(process);
        },
        removeProcess : function (process) {
            celebrio.arrays.remove(process, celebrio.applications.processes);
        },
        
        /*
         * celebrio.applications.create
         * creates new process and adds it into celebrio.applications.processes array
         */
        create : function (name, windowed) {
            
            if (!windowed) {
                windowed = false;
            }
            process = new celebrio.applications.process(celebrio.applications.newPid());
            process.setName(name);
            process.setWindowed(windowed);
            celebrio.applications.addProcess(process);
            for (var listener in celebrio.applications.listeners) {
                celebrio.applications.listeners[listener].create(process);
            }
            return process;
        },
        
        /*
         * celebrio.applications.findProcess
         * searches the process with specified name in the processes array
         * returns process if it is in the array, returns null otherwise
         */
        findProcess : function (name) {
            for(var i in celebrio.applications.processes) {
                if(celebrio.applications.processes[i].getName() == name) {
                    return celebrio.applications.processes[i];
                }
            }
            return null;
        },
        
        /*
         * celebrio.applications.createSingle
         * searches for the process in processes array
         * if process is found, unminimizes it and if not, new process is created
         */
        createSingle : function(name, windowed) {
            for(var i in celebrio.applications.processes) {
                process = celebrio.applications.findProcess(name)
                if(process) {
                    process.toggle();
                    return {
                        "process": process, 
                        "created" : false
                    };
                }
            }
            return {
                "process": celebrio.applications.create(name, windowed), 
                "created" : true
            };
        },
        
        /*
         * celebrio.applications.createWindow
         * creates or unminimalizes the process specified by name
         * if process is newly created, it:
         *      creates new html element with class dialogApplication
         *      append this element to element #desktopWrapper     
         */
        createWindow : function(name, title, content, options) {
            if(options == undefined) {
                options = {};
            }
            var info = celebrio.applications.createSingle(name, true);
            process = info.process;            
            if(info.created == true) {
                var app = $("<div id='"+celebrio.applications.APPLICATION+process.getId()+"' class='dialogApplication' title='"+title+"'>"+content+"</div>")
                .appendTo($("#desktopWrapper")).celebrioApp();
                $(app).find('.resizable').width($(app).width()).height($(app).height());
                celebrio.applications.setFocus(process);
                
                loader = new celebrioLoader(title, options.image, true, $("#desktopWrapper"));
                loader.create();
				
                $(app).find("iframe").load(function() {
                    if (typeof loader != 'undefined') {
                        loader.remove();
                        delete loader;
                    }
                   
                    
                    if(celebrio.applications.focus!=null && celebrio.applications.focus.name == name){
                        history.replaceState({
                            "name" : name,
                            "title" : title,
                            "image" : options.image
                        }, name, "#"+this.contentWindow.location);
                    }
                    
                    var exit_button = $(this).contents().find(".exit_application");
                    if(exit_button.length == 0) {
                        console.log("WARNING: The application does not have any EXIT element. Use 'exit_application' class to fix this.")
                    } else {
                        // exit button holds another action in registration app so we cannot unbind the other actions
                        exit_button.unbind('mousedown', celebrio.applications.exitApplication);
                        exit_button.mousedown(function(button){
                            if(button.which == 1)
                                celebrio.applications.exitApplication();
                        });
                    }
                });
            } else {
                $("#"+celebrio.applications.APPLICATION+process.getId()).find("iframe").trigger('load');
            }
            
            return process;
        },
        createFromHtml : function(name, title, html, options) {
            return celebrio.applications.createWindow(name, title, html, options);
        },
        createFromUrl : function(name, title, url, options) {
            //alert(options);
            return celebrio.applications.createFromHtml(name, title, "<iframe src='"+url+"' class='resizable' />",options);
        },
        run : function (name, title, url, options) {
            
            celebrio.desktop.icons.setFocus(url);
            $(".albireoicon").fadeOut("slow");
            $("#taskbar").fadeOut("slow");
            $("#scrollbar").fadeOut("slow");
            process = celebrio.applications.createFromUrl(name, title, url, options);
            history.pushState({
                "name" : name,
                "title" : title,
                "image" : options.image
            }, name, "#"+$("#"+celebrio.applications.APPLICATION+process.getId()).find("iframe").get(0).src);
            if($("#dummy_layout") != undefined) {
                $("#dummy_layout").fadeIn("slow");  
            }            
        },
        //TODO: temporary solution!
        process : function (id,name) {
            this.id = id;
            this.name = name;
            this.windowed = false;
            this.focus = false;
            var self = this;
			
            this.equals = function(process) {
                //TODO: should take care that object is really process type - better type recognition
                if (process == null ) return false;
                if (this.getId() === process.getId()) {
                    return true;
                }
                return false;
            };
	
            this.getId = function () {
                return this.id;
            };
		
            this.getName = function () {
                return this.name;
            };
	
            this.setName = function (name) {
                this.name = name;
            };
			
            this.isWindowed = function () {
                return this.windowed;
            };
			
            this.setWindowed = function(windowed) {
                this.windowed = windowed;
            };
            
            /*
             * celebrio.applications.process.toggle
             * if this process is focused, minimizes it and vice versa
             * if process is minimalized, celebrio.focus is set to null
             */
            //TODO: should this have any application? some of them are not windowed or can be gadgets...
            //Window can  be observer of process
            this.toggle = function () {
                //TODO: shouldnt be done by dialogs attributes??? More information than really needed OR delegation to "Window"
                if (self.isWindowed()) {
                    if (self.equals(celebrio.applications.focus)) {
                        $("#"+celebrio.applications.APPLICATION+self.getId()).celebrioApp("minimize");
                        celebrio.applications.setFocus(null);
                    } else {
                        $("#"+celebrio.applications.APPLICATION+self.getId()).celebrioApp("unminimize");
                        celebrio.applications.setFocus(self);
                    }
                }
            };

            
            this.focus = function () {
                celebrio.applications.setFocus(self);
            };

            this.close = function() {
                for (var listener in celebrio.applications.listeners) {
                    celebrio.applications.listeners[listener].close(self);
                }
			
                //TODO: maybe also an observer
                if (self.isWindowed()) {
                    $("#"+celebrio.applications.APPLICATION+self.getId()).remove();
                }
                celebrio.applications.removeProcess(self);
                //TODO: always return false to prevent link or event stop propagation?
                return false;
            };
        },
        newPid : function () {
            return ++celebrio.applications.pid;
        }
    },
    
    
    /*
     * celebrio.applications.arrays
     * object for manipulation with arrays in celebrio.application e.g. processes, listeners
     */
    this.arrays = {
        find : function(what, where) {
            if (what == null) {
                return false;
            }
            for (var i in where) {
                if (what.equals(where[i])) {
                    return i;
                }
            }
            return false;
        },
		
        remove : function(what, where)  {

            which = celebrio.arrays.find(what, where);
            if (which) {
                //removes the which element from where
                where.splice(which, 1);
            }
        }
    },
    
    this.keys = {
        "ctrl" : false,
        "init" : function() {
            $(document).keydown(function(event) {
                if (event.ctrlKey) {
                    celebrio.keys.ctrl = true;
                }	
            }).keyup(function(event) {
                if(event.which == 17) {
                    celebrio.keys.ctrl = false;
                }
            });
        }
    }
}

initfnc = function () {
    if (typeof document.body.onselectstart!="undefined")
        document.body.onselectstart=function(){
            return false
        }
    else if (typeof document.body.style.MozUserSelect!="undefined")
        document.body.style.MozUserSelect="none";
    
    celebrio = new Celebrio();
    if(isAndroidClient)
        celebrioForAndroid(celebrio);
    celebrio.desktop.setElement($("#desktop"));
    celebrio.desktop.setColor("#000");
    celebrio.desktop.display(url);
    celebrio.desktop.createIcons();
    celebrio.keys.init(); 

    $(window).bind( 'hashchange', function(e) { 
        window.location.replace(window.location.href);
        celebrio.desktop.checkHistory();
    });
    
    $(window).resize( function () {
        celebrio.desktop.display(url);
        id = celebrio.desktop.getElement();
        id.height($(window).height());
        celebrio.desktop.icons.resize();
        
        if($("#loader").length > 0){
            loader.refresh();
        }
        	
        $(".dialogApplication iframe").css({
            "height" : $(window).height(), 
            "width" : $(window).width()
        });
    });
}

$(document).ready(initfnc);
